package com.webex.ta.hydra.core.macro;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import com.thoughtworks.xstream.mapper.CannotResolveClassException;
import com.webex.ta.hydra.core.Command;


import java.io.*;
import java.nio.charset.Charset;
import java.util.Vector;

/**
 * Created by Cisco WebEx.
 * User: vegaz
 * Date: 2010-9-14
 * Time: 15:07:27
 */
public class MacroSerializer {
    private static String fileEncoding = "UTF-8";

    private static final XStream saver = new XStream(new DomDriver());
    static {
        saver.autodetectAnnotations(true);
        saver.processAnnotations(Command.class);
        saver.processAnnotations(MacroDefinition.class);
    }

    public static void saveMacroDefinitions(Vector<MacroDefinition> defs, OutputStream out) throws IOException {
        OutputStreamWriter outputStreamWriter =
                new OutputStreamWriter(out, Charset.forName("UTF-8"));
        saver.toXML(defs, outputStreamWriter);
		outputStreamWriter.write('\n');
		outputStreamWriter.close();
    }
    
    public static Vector<MacroDefinition> loadMacroDefinitions(InputStream reader) throws Exception {
		if (!reader.markSupported()) {
			reader = new BufferedInputStream(reader);
		}
		reader.mark(Integer.MAX_VALUE);
		Vector<MacroDefinition> defs = null;
		try {
			// Get the InputReader to use
			InputStreamReader inputStreamReader = getInputStreamReader(reader);
			defs = (Vector<MacroDefinition>) saver.fromXML(inputStreamReader);
			inputStreamReader.close();
			return defs;
		} catch (CannotResolveClassException e) {
            e.printStackTrace();
            return null;
		} catch (NoClassDefFoundError e) {
			return null;
		}
	}


    private static Charset getFileEncodingCharset() {
		// Check if we have a encoding to use from properties
		if(fileEncoding != null && fileEncoding.length() > 0) {
			return Charset.forName(fileEncoding);
		}
		else {
			// We use the default character set encoding of the JRE
			return null;
		}
	}

    private static InputStreamReader getInputStreamReader(InputStream inStream) {
		// Check if we have a encoding to use from properties
		Charset charset = getFileEncodingCharset();
		if(charset != null) {
			return new InputStreamReader(inStream, charset);
		}
		else {
			// We use the default character set encoding of the JRE
			return new InputStreamReader(inStream);
		}
	}
}
